package com.navinfo.platform.etl.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

/**
 * 时间转换类
 */
public class DateUtils {

    public static final String DEFAULT_DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";

    public static String format(long mills, String pattern){
       return DateFormatThreadLocal.getFormat(pattern).format(mills);
    }

    public static String format(long mills){
        return DateFormatThreadLocal.getFormat().format(mills);
    }

    public static String format(Date date){
        return DateFormatThreadLocal.getFormat().format(date);
    }

    public static String format(Date date, String pattern){
        return DateFormatThreadLocal.getFormat(pattern).format(date);
    }

    private static class DateFormatThreadLocal {
        private static ThreadLocal<SimpleDateFormat> THREAD_SAFE_FORMATTER = new ThreadLocal<SimpleDateFormat>(){
            @Override
            protected synchronized SimpleDateFormat initialValue() {
                SimpleDateFormat sd = new SimpleDateFormat(DEFAULT_DATETIME_FORMAT);
                sd.setTimeZone(TimeZone.getTimeZone("GMT+8"));
                return sd;
            }
        };

        public static SimpleDateFormat getFormat(){
            return THREAD_SAFE_FORMATTER.get();
        }

        public static SimpleDateFormat getFormat(String pattern){
            SimpleDateFormat format = getFormat();
            format.applyPattern(pattern);
            return format;
        }
    }
}
